'use strict';
module.exports = {
	/**
	 * 删除记账数据
	 * @url client/accounting/record/kh/delKeepingData 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _, $ } = util;
		let { uid,relationId, dataInf,accountBook } = data;
		let res = { code: 0, msg: "删除失败" };
		// 业务逻辑开始-----------------------------------------------------------
		
		if(pubFun.isEmpty(accountBook) || pubFun.isEmpty(relationId) || pubFun.isEmpty(dataInf)){
			return { code : 1001, msg : '参数错误' };
		}
		
		const paramUtil = vk.require("service/client/accountbook/util/paramUtil");
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 新增记账数据
			const row = await vk.daoCenter.bookKeepingDataDao.deleteById(dataInf._id, transaction);
			if (row <= 0) {
				throw new Error("删除失败");
			}
			// 新增关联关系
			const row2 = await vk.daoCenter.bookRelationDataDao.deleteById(relationId, transaction);
			if (row2 <= 0) {
				throw new Error("删除失败");
			}
			
			let _dataJson = {"revision": accountBook.revision + 1}
			if(dataInf.isExpenses === "true") {
				_dataJson.totalEcpenditure = accountBook.totalEcpenditure - dataInf.amount
				_dataJson.surplus  = accountBook.surplus - dataInf.amount
			}
			else {
				_dataJson.totalRevenue = accountBook.totalRevenue - dataInf.amount
				_dataJson.surplus  = accountBook.surplus - dataInf.amount
			}
			_dataJson.totalCount = accountBook.totalCount - 1
			_dataJson = await paramUtil.dealUpdateParam(_dataJson);
			// 更新账本数据
			let row3 = await vk.baseDao.update({
				db: transaction, // 本次数据库语句带上事务对象（重要，必须带上）
				dbName:"db-account-book",
				whereJson: {
					_id: _.eq(accountBook._id)
				},
				dataJson: _dataJson
			 });
			 if (row3 <= 0) {
			 	throw new Error("删除失败" + accountBook._id);
			 }
			
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}